#include "Frustum.h"

namespace devii
{
	
Frustum::Frustum()
{
}

Frustum::~Frustum()
{
}


D3DXMATRIX Frustum::getProjection(){
	return projection;
}

void Frustum::setFrustum( D3DXMATRIX view ){
	D3DXMATRIX M;
	D3DXMatrixMultiply(&M, &view, &projection);

	//Left plane
	frustum[0].a = -(M._14 + M._11);
	frustum[0].b = -(M._24 + M._21);
	frustum[0].c = -(M._34 + M._31);
	frustum[0].d = -(M._44 + M._41);

	//Right plane
	frustum[1].a = -(M._14 - M._11);
	frustum[1].b = -(M._24 - M._21);
	frustum[1].c = -(M._34 - M._31);
	frustum[1].d = -(M._44 - M._41);

	//Bottom plane
	frustum[2].a = -(M._14 + M._12);
	frustum[2].b = -(M._24 + M._22);
	frustum[2].c = -(M._34 + M._32);
	frustum[2].d = -(M._44 + M._42);


	//Top plane
	frustum[3].a = -(M._14 - M._12);
	frustum[3].b = -(M._24 - M._22);
	frustum[3].c = -(M._34 - M._32);
	frustum[3].d = -(M._44 - M._42);

	//Near plane
	frustum[4].a = -( M._14 + M._13);
	frustum[4].b = -( M._24 + M._23);
	frustum[4].c = -( M._34 + M._33);
	frustum[4].d = -( M._44 + M._43);

	//Far plane
	frustum[5].a = -(M._14 - M._13);
	frustum[5].b = -(M._24 - M._23);
	frustum[5].c = -(M._34 - M._33);
	frustum[5].d = -(M._44 - M._43);

	//Normalize planes.
	/*for(int i = 0; i < 6; i++){
		float3 Normal(frustum[i].a, m_frustum[i].b, m_frustum[i].c);

		float denom = 1.0f / D3DXVec3Length(&Normal);

		m_frustum[i].a *= denom;
		m_frustum[i].b *= denom;
		m_frustum[i].c *= denom;
		m_frustum[i].d *= denom;
	}*/
}

void Frustum::setProjection(float fovy, float aspect, float zn, float zf){
	float yScale, xScale;

	yScale = 1 / tan( fovy / 2 );
	xScale = ( yScale / aspect );

	projection = D3DXMATRIX	(	xScale,		0.0f,		0.0f,					0.0f,
									0.0f,		yScale,		0.0f,					0.0f,
									0.0f,		0.0f,		zf / ( zf - zn ),		1.0f,
									0.0f,		0.0f,		-zn * zf / ( zf - zn ),	0.0f
								);
	//D3DXMatrixPerspectiveFovLH( &m_projection, fovy, aspect, zn, zf );
}

float Frustum::distanceToPlane( float3 &point, D3DXPLANE &plane ){
	float distance = 0.0f;
	distance = plane.a * point.x + plane.b * point.y + plane.c * point.z + plane.d;

	return distance;
}

}